package com.smarth.zhizulian.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.gyf.barlibrary.ImmersionBar;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.adapter.MyPagerAdapter;
import com.smarth.zhizulian.app.BaseActivity;
import com.smarth.zhizulian.bean.profit.ProfitUserProfit;
import com.smarth.zhizulian.entity.CashRoll;
import com.smarth.zhizulian.fragment.GetMoneyFragment;
import com.smarth.zhizulian.fragment.MoneyDetailFragment;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.popupwindow.FriendHongBaoDialog;
import com.smarth.zhizulian.utils.KumaLog;
import com.smarth.zhizulian.utils.KumaToast;
import com.smarth.zhizulian.utils.MoneyUtils;
import com.smarth.zhizulian.utils.TimeUtils;
import com.smarth.zhizulian.utils.listhelper.RefreshHelper;
import com.smarth.zhizulian.utils.listhelper.impl.adapter.PageDataAdapter;
import com.smarth.zhizulian.utils.listhelper.impl.model.HttpPageDataModel;
import com.smarth.zhizulian.view.LoadingLayout;
import com.ogaclejapan.smarttablayout.SmartTabLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * Created by 18865 on 2017/12/27.
 */

public class MoneyDetailActivity extends BaseActivity {
    @BindView(R.id.tl_tablayout)
    SmartTabLayout tlTablayout;
    @BindView(R.id.vp_viewpager)
    ViewPager vpViewpager;
    MyPagerAdapter pagerAdapter;
    @BindView(R.id.tv_today)
    TextView tvToday;
    @BindView(R.id.tv_yestoday)
    TextView tvYestoday;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.ll_loadinglayout)
    LoadingLayout llLoadinglayout;
    @BindView(R.id.titlebar_all)
    LinearLayout titlebarAll;
    @BindView(R.id.tv_lefttime)
    TextView tvLefttime;
    @BindView(R.id.iv_getmoney)
    ImageView ivGetmoney;
    @BindView(R.id.vf_ad)
    ViewFlipper vfAd;
    private RefreshHelper<ProfitUserProfit> refreshHelper;
    private Disposable mDisposable;

    private int mMode;
    public static final int MODE_MONEYDETAIL = 0;
    public static final int MODE_GETMONEY = 1;
    public static final String INTENT_MODE = "INTENT_MODE";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moneydetail);
        ButterKnife.bind(this);
        setTitlebar("收支明细", true);
        initTab();
        init();
//        initAd();
//        new FriendHongBaoDialog(mContext, 1000, 10).show();
    }

    private void initAd(List<CashRoll> list) {
        vfAd.removeAllViews();
        for (CashRoll cr : list) {
            View view = LayoutInflater.from(this).inflate(R.layout.flipper_moneydetail_ad, null);
            TextView tv_name = view.findViewById(R.id.tv_name);
            TextView tv_money = view.findViewById(R.id.tv_money);
            tv_name.setText(cr.getAppUserName() + "通过微信提现");
            tv_money.setText(MoneyUtils.coin2Money(cr.getCashCoin()) + "元");
            vfAd.addView(view);
        }
    }

    @Override
    protected void initStatusBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()
                .statusBarDarkFont(true)
                .fitsSystemWindows(false)
                .init();
    }

    private void init() {
        refreshHelper = new RefreshHelper<>(mContext, llLoadinglayout, null);
        refreshHelper.setDataModel(new HttpPageDataModel<ProfitUserProfit>(mContext) {
            @Override
            public Observable<ProfitUserProfit> getObservable() {
                return KumaHttp.getService().profitUserProfit().compose(RxCompos.<ProfitUserProfit>getBELoginCompos())
                        .doOnError(new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                titlebarAll.setVisibility(View.VISIBLE);
                            }
                        }).doOnNext(new Consumer<ProfitUserProfit>() {
                            @Override
                            public void accept(ProfitUserProfit profitUserProfit) throws Exception {
                                titlebarAll.setVisibility(View.GONE);
                            }
                        });
            }
        });
        refreshHelper.setDataAdapter(new PageDataAdapter<ProfitUserProfit>() {
            @Override
            public void onGetData(final ProfitUserProfit profitUserProfit, boolean isRefresh) {
                super.onGetData(profitUserProfit, isRefresh);
                tvToday.setText(MoneyUtils.coin2Money(profitUserProfit.getTodayCoin()));
                tvYestoday.setText(MoneyUtils.coin2Money(profitUserProfit.getYesterdayCoin()));
                tvLeft.setText(MoneyUtils.coin2Money(profitUserProfit.getCoin()));
                initAd(profitUserProfit.getCashRolls());
                if (profitUserProfit.getLastCashApplyDateTime() > 0) {
                    tvLefttime.setVisibility(View.VISIBLE);
                    ivGetmoney.setEnabled(false);
                    tvLefttime.setText(Html.fromHtml(TimeUtils.getLeftTime(profitUserProfit.getLastCashApplyDateTime()) + "可提现"));
                    final long count = profitUserProfit.getLastCashApplyDateTime() / 1000;
                    Observable.interval(0, 1, TimeUnit.SECONDS)
                            .take(count + 1) //设置循环
                            .map(new Function<Long, Long>() {
                                @Override
                                public Long apply(@NonNull Long aLong) throws Exception {
                                    return profitUserProfit.getLastCashApplyDateTime() - (aLong * 1000); //
                                }
                            })
                            .doOnSubscribe(new Consumer<Disposable>() {
                                @Override
                                public void accept(Disposable disposable) throws Exception {
                                    tvLefttime.setVisibility(View.VISIBLE);
                                    ivGetmoney.setEnabled(false);//在发送数据的时候设置为不能点击
                                }
                            })
                            .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                            .subscribe(new Observer<Long>() {
                                @Override
                                public void onSubscribe(@NonNull Disposable d) {
                                    mDisposable = d;
                                }

                                @Override
                                public void onNext(@NonNull Long aLong) {
//                                Log.d(TAG, "onNext: " + aLong);
                                    tvLefttime.setText(Html.fromHtml(TimeUtils.getLeftTime(aLong) + "可提现"));
                                    ivGetmoney.setEnabled(false);
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {
                                    e.printStackTrace();
//                                    tvGetcode.setText("获取验证码");//数据发送完后设置为原来的文字
                                    ivGetmoney.setEnabled(true);
                                    KumaToast.showError(mContext, e.getMessage());
                                }

                                @Override
                                public void onComplete() {
//                                    tvGetcode.setText("获取验证码");//数据发送完后设置为原来的文字
                                    tvLefttime.setVisibility(View.GONE);
                                    ivGetmoney.setEnabled(true);
                                }
                            });
                } else {
                    tvLefttime.setVisibility(View.GONE);
                    ivGetmoney.setEnabled(true);
                }

            }
        });
        refreshHelper.refresh();
    }

    private void initTab() {
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new MoneyDetailFragment());
        fragmentList.add(new GetMoneyFragment());
        List<String> titleList = new ArrayList<>();
        titleList.add("收益明细");
        titleList.add("提现记录");
        pagerAdapter = new MyPagerAdapter(mContext, getSupportFragmentManager(), fragmentList, titleList);
        vpViewpager.setAdapter(pagerAdapter);
        tlTablayout.setViewPager(vpViewpager);

        if (getIntent().getIntExtra(INTENT_MODE, MODE_MONEYDETAIL) == MODE_GETMONEY) {
            vpViewpager.setCurrentItem(1);
        }
    }

    public static void open(Context context) {
        Intent i = new Intent(context, MoneyDetailActivity.class);
        i.putExtra(INTENT_MODE, MODE_MONEYDETAIL);
        context.startActivity(i);
    }

    public static void openForGetMoney(Context context) {
        Intent i = new Intent(context, MoneyDetailActivity.class);
        i.putExtra(INTENT_MODE, MODE_GETMONEY);
        context.startActivity(i);
    }

    @OnClick({R.id.iv_back, R.id.iv_getmoney})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                this.finish();
                break;
            case R.id.iv_getmoney:
                GetMoneyCenterActivity.open(mContext);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            KumaLog.kuma("mDisposable");
            mDisposable.dispose();
        }
        super.onDestroy();
    }
}
